package org.baicaixiaozhan.tenet.http;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * IP 工具集
 *
 * @author baicaixiaozhan
 * @since 1.0.0
 */
public final class IPs {

    private static final String REGX_IP = "((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";
    private static final String REGX_IPB = REGX_IP + "\\-" + REGX_IP;
    public static final String UNKNOWN = "unknown";
    public static final String LOCALHOST_MODEL_ONE = "127.0.0.1";
    public static final String LOCALHOST_MODEL_TWE = "0:0:0:0:0:0:0:1";

    private IPs() {
        throw new AssertionError();
    }

    /**
     * 判断目标 IP 是否在指定 IP 段内
     *
     * @param targetIP 示例：192.168.1.255
     * @param IPRange 示例：192.168.1.120-192.168.1.254
     * @return boolean
     */
    public static boolean isIpWithinRange(String targetIP, String IPRange) {
        Preconditions.checkNotNull(IPRange, "IP段不能为空");
        Preconditions.checkNotNull(targetIP, "IP不能为空");

        IPRange = IPRange.trim();
        targetIP = targetIP.trim();

        if (!IPRange.matches(REGX_IPB) || !targetIP.matches(REGX_IP)) {
            return false;
        }
        int idx = IPRange.indexOf('-');
        String[] sips = IPRange.substring(0, idx).split("\\.");
        String[] sipe = IPRange.substring(idx + 1).split("\\.");
        String[] sipt = targetIP.split("\\.");
        long ips = 0L, ipe = 0L, ipt = 0L;
        for (int i = 0; i < 4; ++i) {
            ips = ips << 8 | Integer.parseInt(sips[i]);
            ipe = ipe << 8 | Integer.parseInt(sipe[i]);
            ipt = ipt << 8 | Integer.parseInt(sipt[i]);
        }
        if (ips > ipe) {
            long t = ips;
            ips = ipe;
            ipe = t;
        }
        return ips <= ipt && ipt <= ipe;
    }

    /**
     * 获取目标请求 IP 地址
     *
     * @param request 目标请求
     * @return IP 地址
     * @throws UnknownHostException 未知 host 异常
     */
    public static String getIPAddress(HttpServletRequest request) throws UnknownHostException {
        String ip = request.getHeader("x-forwarded-for");
        if (Strings.isNullOrEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (Strings.isNullOrEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (Strings.isNullOrEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (LOCALHOST_MODEL_TWE.equals(ip) || LOCALHOST_MODEL_ONE.equals(ip)) {
            ip = InetAddress.getLocalHost().getHostAddress();
        }
        return ip;
    }
}
